package com.duck.gateway.filters;

import com.duck.common.exception.UnauthorizedException;
import com.duck.gateway.config.AuthProperties;
import com.duck.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component //注册成bean
@RequiredArgsConstructor //函数构造器
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    //第一个参数是当前请求的上下文，其中包含request、response等各种数据
    //第二个参数是过滤器链，基于它向下传递请求
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1,获取request
        ServerHttpRequest request = exchange.getRequest();
        //2,判断是否需要做登录拦截（有的请求不需要token就能访问）
        if(isExclude(request.getPath().toString())){
            //放行
            return chain.filter(exchange);
        }
        //3,判断到是需要拦截的请求后，获取请求的token
        String token = null;
        List<String> tokenHeaders = request.getHeaders().get("token");
        if (tokenHeaders != null && !tokenHeaders.isEmpty()) {
            token = tokenHeaders.get(0);
            System.out.println("Received token: " + token); // 打印原始token
        } else {
            List<String> authHeaders = request.getHeaders().get("authorization");
            if (authHeaders != null && !authHeaders.isEmpty()) {
                token = authHeaders.get(0);
            }
        }
        //4,检验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
            System.out.println("Parsed userId: " + userId);
        } catch (UnauthorizedException e) {
            // 如果无效，拦截，设置响应状态码为401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5.如果有效，传递用户信息
        String userInfo = userId.toString();
        ServerWebExchange ex = exchange.mutate() //在获取用户信息后保存到请求头，转发到下游微服务
                .request(b -> b.header("user-info",userInfo))
                .build();
        //6，放行
        return chain.filter(ex);
    }

    @Override
    public int getOrder() {
        //这个方法是声明这个函数（过滤器）的执行顺序的，值越小。优先级越高
        return 0;
    }

    //判断请求的路径是否匹配
    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){ //使用spring框架提供的工具包来匹配路径是否需要拦截
                return true;
            }
        }
        return false;
    }
}
